angular.module('furion.services.api', [])

.factory("RHTTP", (Config, $state, $rootScope, Toast, $ionicPopup) ->
  rhttp = {}

  checkConn = ->
    return unless furion.utils.isDevice()
    networkState = navigator.connection.type

    states = {}
    states[Connection.UNKNOWN]  = '未知类型连接';
    states[Connection.ETHERNET] = '以太网';
    states[Connection.WIFI]     = 'WiFi';
    states[Connection.CELL_2G]  = '2G';
    states[Connection.CELL_3G]  = '3G';
    states[Connection.CELL_4G]  = '4G';
    states[Connection.CELL]     = '蜂窝数据连接';
    states[Connection.NONE]     = '无连接';

    console.log('Connection type: ' + states[networkState]);
    # Toast.show('Connection type: ' + states[networkState]);

    if Connection.NONE == networkState || Connection.UNKNOWN == networkState
      $rootScope.$emit "networkconn:none"
      Toast.show "无网络连接，请检查手机设置"

    if Connection.CELL == networkState ||
       Connection.CELL_2G == networkState ||
       Connection.CELL_3G == networkState ||
       Connection.CELL_4G == networkState
      $rootScope.$emit "networkconn:cell"

  rhttp.p = (url, data, config={})->
    data = data or {}
    data.client_version = Config.version
    data.market_vendor = Config.market_vendor
    data.session_id = furion.storage.account().session_id
    if device?
      data.device = {}
      data.device.available = device.available
      data.device.cordova = device.cordova
      data.device.isVirtual = device.isVirtual
      data.device.manufacturer = device.manufacturer
      data.device.model = device.model
      data.device.platform = device.platform
      data.device.serial = device.serial
      data.device.uuid = device.uuid
      data.device.version = device.version
    data.jpush_token = furion.storage.deviceInfo().jpush_token

    if window.plugins && window.plugins.jPushPlugin
      if !data.jpush_token? || data.jpush_token == ""
        furionPush.jpush.getRegistrationID()

    $rootScope.load_status = null

    console.debug "api: #{url} post data is: "
    console.debug data

    $.ajax(
      type: 'POST'
      url: url
      data: data
      async: (config.is_async != false)
    ).done( (ret) ->
      $rootScope.load_status = 1
      # do something
      console.debug "api: #{url} get data is: "
      console.debug ret
    ).fail( (err) ->
      $rootScope.load_status = 0

      # Toast.show "#{err.status}: #{err.responseText}"

      switch err.status
        when 0
          checkConn()
          $rootScope.$emit "loading:hide"

        when 404 # 地址不存在
          Toast.show '访问地址不存在'
          $rootScope.$emit "loading:hide"
          throw "stop post chain"

        when 503 # 通用提示错误
          try
            ret = JSON.parse(err.responseText)
            Toast.show ret.status.msg
          catch
            Toast.show '网络不稳定，请稍后重试'

          $rootScope.$emit "loading:hide"
          throw "stop post chain"

        when 502 # 自定义错误，由具体 API 处理
          console.debug  "#{err.responseText}"

        when 500 # 系统错误
          try
            ret = JSON.parse(err.responseText)
            Toast.show ret.status.msg
          catch
            console.log "解析json失败"

        when 501 # 系统定义错误
          try
            ret = JSON.parse(err.responseText)
            switch ret.data.error_type
              when 1 # session 过期，或者需要登陆
                furion.storage.deleteAccount()
                $rootScope.$emit('close-all-modals')
                $rootScope.$emit("modals:open", {modal_name: 'signin', params: {state: 'app.account'}})
              when 2 # 有新版本，需要强制升级
                cfg = ret.data.detail
                furion.utils.upgradeApp(cfg, $ionicPopup)
              else
                console.log "未知错误类型: #{ret.data.error_type}, 错误信息 #{ret.status.msg}"
                # Toast.show "未知错误类型: #{ret.data.error_type}, 错误信息 #{ret.status.msg}"
                break
          catch err2
            console.log "解析json失败:#{err2}"
            # Toast.show '网络不给力哦'
        else # 其他状态码错误
          console.log "尚未定义的错误状态：#{err.status}"
    ).complete( (e)->
      $rootScope.$digest() unless $rootScope.$$phase
    )

  rhttp.h = (url, data, config = {})->
    remote_server_version = config.version || Config.remote_server_default_version
    url = [Config.remote_server, remote_server_version, url].join('/')
    rhttp.p(url, data, config)

  return rhttp
)

.factory("RemoteSrv", (RHTTP, Config) ->
  {
    mock: (params) ->
      RHTTP.h "p.json", params

    getFrontPicture: ()->
      RHTTP.h '/front_pictures'

    getWechatToken: (url)->
      RHTTP.h "/wechat_token", {url: url}, {is_async: false}

    getActivityList: (page)->
      RHTTP.h "/activities/list", {page: page}

    getActivityInfo: (cname)->
      RHTTP.h "/activities/info", {cname: cname}

    getAnnouncementList: (page)->
      RHTTP.h "/announcements/list", {page: page}

    getAccountObjectList: (params) ->
      RHTTP.h "/objects/list", params

    getAccountObjectDetail: (obj_id, params) ->
      RHTTP.h "/object/#{obj_id}", params

    signin: (params)->
      RHTTP.h "/signin", params

    signup: (account) ->
      RHTTP.h "/signup", account

    signout: () ->
      RHTTP.h "/signout"

    getValidationCode: (phone, reason) ->
      RHTTP.h "/vcodes", {phone: phone, usage: reason}

    verifyVcode: (phone, usage, vcode) ->
      RHTTP.h '/vcodes/verify', {phone: phone, usage: usage, vcode: vcode}

    checkQuans: (params) ->
      RHTTP.h "/quans/check", params

    getQuans: (type) ->
      RHTTP.h "/quans/list", {type: type}

    createBankcard: (info)->
      RHTTP.h "/bankcards/create", info

    createPayPwd: (new_pwd)->
      RHTTP.h "/passwords/pay/create", {password: new_pwd}

    resetPayPassword: (code, password)->
      RHTTP.h "/passwords/pay/reset", {vcode: code, password: password}

    resetPassword: (params)->
      RHTTP.h "/passwords/signin/reset", params

    resetGesture: (params) ->
      RHTTP.h "/gesture/reset", params

    setGesture: (params) ->
      RHTTP.h "/gesture/set", params

    getHomeAnnouncements: ()->
      RHTTP.h "/announcements/home/get"

    getHomeImgs: ()->
      RHTTP.h "/products/assemblys/imgs_with_url"

    getFirstpageProductFixeds: () ->
      RHTTP.h "/products/fixeds/firstpage"

    getProductFixed: (id) ->
      RHTTP.h "/products/fixeds/get", {obj_id: id}

    getProductsFixed: (category) ->
      RHTTP.h "/products/fixeds/list", {asset_category: category}

    getConditions: (aid) ->
      RHTTP.h "/risk/get/conditions", {aid: aid}

    getAccountInfo: () ->
      RHTTP.h "/account/info"

    setNickname: (nickname) ->
      RHTTP.h '/account/vname/set', {vname: nickname}

    getTotalAmountDetail: () ->
      RHTTP.h "/asset/account/amount_detail"

    moneyRecharge: (params) ->
      RHTTP.h "/money/recharge", params

    moneyWithdraw: (params) ->
      RHTTP.h "/money/withdraw", params

    calWithdrawFee: (amount) ->
      RHTTP.h "/money/cal_withdraw_fee", {amount: amount}

    doPrerequisite: (params)->
      RHTTP.h "/money/prerequisite", params

    payDelegate: (params) ->
      RHTTP.h "/delegate/pay", params

    getProtocal: (type, id, asset_id, transfer_id)->
      RHTTP.h "/protocals/get", {type: type, protocal_id: id, asset_id: asset_id, transfer_id: transfer_id}

    feedback: (feedback) ->
      RHTTP.h "/feedback", feedback

    getFAQ: () ->
      RHTTP.h "/FAQ"

    getBankcardLimit: (channel = 'summary') ->
      RHTTP.h "/payments/limit/" + channel

    getSpreadInfo: () ->
      RHTTP.h "/account/spread/info"

    getSpreadList: ()->
      RHTTP.h "/account/spread/list"

    getRank: ()->
      RHTTP.h "/account/spread/rank"

    setTouchid: (params) ->
      RHTTP.h "/touchid/set", params

    getCpmConfig: (page)->
      RHTTP.h "/cpm_config/get", {page: page}

    createDebtTransferProduct: (id, amount, interest)->
      RHTTP.h "/transfers/create", {asset_id: id, amount: amount, wanted_interest: interest}

    cancelDebtTransfer: (id)->
      RHTTP.h "/transfers/#{id}/cancel"

    getMyTransferList: (params)->
      RHTTP.h "/transfers/mine", params

    getTransferProductsList: (params)->
      RHTTP.h "/transfers/list", params

    getTransferProduct: (id)->
      RHTTP.h "/transfers/get/#{id}"

    getTransferExplain: (id)->
      RHTTP.h "/transfers/explain"
  }
)
